package com.hx.thread.sync;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.stream.IntStream;

/**
 * @author Minghua Chen
 * @date 2020-09-01 23:00
 */
public class SyncExample2 {
    public List<String> list = new ArrayList<>();

    public static void main(String[] args) throws InterruptedException {
//        SyncExample2 example2 = new SyncExample2();
//        example2.take();
//        example2.give("a");
        LongAccumulator accumulator = new LongAccumulator((x, y) -> x * y, 1);
        ExecutorService executor = Executors.newFixedThreadPool(8);
        IntStream.range(1, 10).forEach(i -> executor.submit(() -> accumulator.accumulate(i)));

        Thread.sleep(2000);
        System.out.println(accumulator.getThenReset());

    }

    public void give(String data) {
        synchronized (this) {
            list.add(data);
            notify();
        }
    }

    public String take() throws InterruptedException {
        synchronized (this) {
            // while (list.isEmpty()) {
            wait(); // wait会释放锁  但无法执行wait后面的逻辑,后续逻辑是阻塞的
            //  }
            return list.get(0);
        }
    }
}
